package com.cloudkinto.controller.fbaorderoutput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.fbaorderoutput.FbaOrderOutputService;
import com.cloudkinto.service.fbaorderoutput.vo.*;
import com.cloudkinto.service.orderoutput.vo.OrderOutputDetailRes;
import com.cloudkinto.service.orderoutput.vo.OrderOutputExcelReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputListRes;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@RestController
@Api(tags = "fba出库订单模块")
@RequestMapping("/api/fbaOrderOutput")
public class FbaOrderOutputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(FbaOrderOutputController.class);

    @Autowired
    private FbaOrderOutputService service;
    @Autowired
    private StockRecordService stockRecordService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("fbaReturnAdd")
    @ApiOperation(value = "fba转运新增", notes = "新增")
    public SingleResult fbaReturnAdd(@RequestBody @Validated FbaOrderOutputAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        req.setCompanyId(companyId);
        String value = service.fbaStorageAdd(req, userId);
        if (value == null) {
            return SingleResult.success("新增成功");
        } else {
            return SingleResult.failure(value);
        }
    }

    @UserSessionRequired
    @PostMapping("computationalCosts")
    @ApiOperation(value = "费用预算", notes = "费用预算")
    public SingleResult computationalCosts(@RequestBody @Validated FbaOrderOutputComputationalCostsReq req) {
        Long companyId = getCompanyId();
        return SingleResult.success(service.computationalCosts(req, companyId));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id, getCompanyId());
    }

    @UserSessionRequired
    @PutMapping("/update")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated FbaOrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PostMapping("/set/appointmentStorageTime")
    @ApiOperation(value = "设置约仓时间", notes = "修改")
    public SingleResult appointmentStorageTime(@RequestBody @Validated FbaOrderOutputUpdateTimeReq req) {
        service.appointmentStorageTime(req);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/set/appointmentCarTime")
    @ApiOperation(value = "设置约车时间", notes = "修改")
    public SingleResult appointmentCarTime(@RequestBody @Validated FbaOrderOutputUpdateTimeReq req) {
        service.appointmentCarTime(req);
        return SingleResult.success();
    }

//    @UserSessionRequired
//    @PutMapping("/order/cutoff/{id}")
//    @ApiOperation(value = "截单", notes = "截单")
//    public SingleResult cutoff(@PathVariable("id") Long id) {
//        Long userId = getCurrentUserId();
//        Long companyId = getCompanyId();
//        service.cutoff(id, userId,companyId);
//        return SingleResult.success(null);
//    }

    @UserSessionRequired
    @GetMapping("/order/salesReturn/init/{id}")
    @ApiOperation(value = "退货初始化", notes = "退货初始化")
    public SingleResult salesReturnInit(@PathVariable("id") Long id) {
        return service.salesReturnInit(id);
    }

//    @UserSessionRequired
//    @PostMapping("/order/salesReturn")
//    @ApiOperation(value = "退货", notes = "截单")
//    public SingleResult salesReturn(@RequestBody FbaOrderOutputSalesReturnReq req) {
//        service.salesReturn(req,getCurrentUserId(),getCompanyId());
//        return SingleResult.success(null);
//    }


    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<FbaOrderOutputDetailRes> detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id, false));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    @ApiImplicitParams(@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pagesize", value = "页大小"),
            @ApiImplicitParam(name = "status", value = "订单状态"),
            @ApiImplicitParam(name = "trackId", value = "快递公司"),
            @ApiImplicitParam(name = "storageType", value = "FBA/B2B"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "startDate", value = "开始时间"),
            @ApiImplicitParam(name = "endDate", value = "结束时间")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputListRes.class)})
    public PageResult<OrderOutputListRes> listPage(String keyword, String current, String pageSize,String storageType,
                                                   String status, String startDate, String endDate, String trackId, String shopId, String storageId) {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", pageSize);
        map.put("status", status);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("trackId", trackId);
        map.put("storageId", storageId);
        map.put("storageType", storageType);
//        map.put("orderType", "2");//fba转运
        if (!StringUtils.isEmpty(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        map.put("companyId", companyId + "");
        return service.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/uploadExcel")
    @ApiOperation(value = "导入发货单Excel", notes = "导入发货单Excel")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadExcel(MultipartFile file, Integer shopId, Integer storageId) {
        Long userid = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.dealwithExcel(file, shopId, storageId, userid, companyId);
    }

    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderOutputExcelReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.getKeyword());
        map.put("current", req.getCurrent());
        map.put("pageSize", req.getPageSize());
        map.put("status", req.getStatus());
        map.put("startDate", req.getStartDate());
        map.put("endDate", req.getEndDate());
        map.put("trackId", req.getTrackId());
        map.put("storageId", req.getStorageId());
//        map.put("orderType", "2");//fba转运
        if (!StringUtils.isEmpty(req.getShopId())) {
            map.put("shopId", req.getShopId());
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        map.put("companyId", companyId + "");
        service.exportExcel(map, req, response);
    }

    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "仓库商品查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String productType = request.getParameter("productType");

        map.put("keyword", keyword);
        map.put("productType", productType);
        map.put("storageId", storageId);
        if (!StringUtils.isEmpty(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("current", current);
        map.put("pageSize", size);
        return stockRecordService.getListPage(map);
    }


    @UserSessionRequired
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入入库单信息", notes = "导入入库单信息")
    public SingleResult uploadExcel(MultipartFile file, Long storageId, Long shopId) throws IOException {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.importExcel(file, storageId, shopId,getCompanyId()));
    }
}

